//引入lodash isArray
import { isArray } from 'lodash';
import { createLayer } from './utils';

const _addOverlay = (addData, { layerId, groupId }, viewer) => {
  let layer = viewer.getLFTLayer(layerId, groupId);
  if (!layer) {
    layer = createLayer(layerId, groupId, viewer);
  }
  for (let i = 0; i < addData.length; i++) {
    const m = addData[i];
    if (layer && DX5S.LFTOverlay[m?.overlayType]) {
      let _overlay = new DX5S.LFTOverlay[m?.overlayType](m);
      layer.addOverlay(_overlay);
    }
  }
};

const drawSimpleOverlay = (drawData, ctrl) => {
  let { payload, layerId = '', groupId = '', viewer } = drawData;
  if (typeof payload === 'string') {
    payload = JSON.parse(payload);
  }
  switch (ctrl) {
    case 'del':
      _delOverlay(payload, { layerId, groupId }, viewer);
      break;
    case 'modify':
      _modifyOverlay(payload, { layerId, groupId }, viewer);
      break;
    default:
      _addOverlay(payload, { layerId, groupId }, viewer);
      break;
  }
};

export function drawLeafletInitFun(drawData, viewer, cb) {
  for (let i = 0; i < drawData.length; i++) {
    let { groupId, layerId, type, payload, layerOptions } = drawData[i];
    switch (type) {
      case 'simple':
      default:
        if (isArray(payload)) {
          drawSimpleOverlay({ layerId, groupId, payload, viewer });
        } else {
          if (payload?.add?.length > 0) {
            drawSimpleOverlay(
              { layerId, groupId, payload: payload.add, viewer },
              'add',
            );
          }
          if (payload.modify?.length > 0) {
            drawSimpleOverlay(
              { layerId, groupId, payload: payload.modify, viewer },
              'modify',
            );
          }
          if (payload.delete?.length > 0) {
            drawSimpleOverlay(
              { layerId, groupId, payload: payload.delete, viewer },
              'del',
            );
          }
        }
        break;
    }
  }
}
